/**
 * Launcher.java | Created on 30 08 2010
 */
package com.pacm;

import com.pacm.letter.Letter;
import com.pacm.assembler.LetterAssembler;
import com.pacm.util.LetterAssemblerFactory;
import com.pacm.util.LetterFactory;
import com.pacm.util.LetterPrinterType;
import com.pacm.util.LetterType;

/**
 * Launches the main application
 *
 * @author Paul Augustine C. Mendoza
 */
public class Launcher {

    private static final LetterType[] LETTERS = {LetterType.LETTER_X, LetterType.LETTER_Y, LetterType.LETTER_Z};
    private static final int MINIMUM = 3;
    private static final int TWO = 2;
    private static int size;
    private static String errorMessage;

    public static void main(String[] args) {
        validateSize(args);
        Letter[] letterArray = getLetterArray();
        printHorizontally(letterArray);
        printVertically(letterArray);
    }

    private static void printHorizontally(Letter[] letterArray) {
        LetterAssembler assembler = LetterAssemblerFactory
                .getPrinter(LetterPrinterType.HORIZONTAL);
        assembler.assemble(letterArray, size);
        System.out.println(assembler.getPrintableString());
    }

    private static void printVertically(Letter[] letterArray) {
        LetterAssembler assembler = LetterAssemblerFactory
                .getPrinter(LetterPrinterType.VERTICAL);
        assembler.assemble(letterArray, size);
        System.out.println(assembler.getPrintableString());
    }

    private static Letter[] getLetterArray() {
        Letter letter;
        Letter[] letterArray = new Letter[LETTERS.length];
        for (int i = 0; i < LETTERS.length; i++) {
            letter = LetterFactory.getLetterWithSize(LETTERS[i], size);
            letterArray[i] = letter;
        }
        return letterArray;
    }

    private static void validateSize(String[] args) {
        if (!isValidParemeter(args)) {
            throw new IllegalArgumentException("Invalid input: " + errorMessage);
        }
    }

    private static boolean isValidParemeter(String[] args) {
        boolean isValid = false;
        if (args.length == 1) {
            try {
                size = Integer.parseInt(args[0]);
                isValid = (!isOdd() && isAtLeastThree());
                if (!isValid) {
                    errorMessage = size + " is not allowed";
                }
            } catch (NumberFormatException nfe) {
                errorMessage = "Input is not a number";
            }
        } else {
            errorMessage = "Invalid argument size";
        }
        return isValid;
    }

    private static boolean isOdd() {
        return (size % TWO) == 0;
    }

    private static boolean isAtLeastThree() {
        return size >= MINIMUM;
    }

}
